package com.gzz.orchid.common.webmvc.converter.enums.factory;


import com.gzz.orchid.common.core.support.IBaseEnum;
import com.gzz.orchid.common.webmvc.converter.enums.IntegerToEnumConverter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 编码 -> 枚举 转化器工厂类
 *
 * @author higmd
 */
public class IntegerToConverterFactory implements ConverterFactory<Integer, IBaseEnum> {
    private static final Map<Class<?>, Converter<Integer, ?>> CONVERTERS = new HashMap<>();

    /**
     * 获取一个从 Integer 转化为 T 的转换器，T 是一个泛型，有多个实现
     *
     * @param targetType 转换后的类型
     * @return 返回一个转化器
     */
    @Override
    public <T extends IBaseEnum> Converter<Integer, T> getConverter(Class<T> targetType) {
        @SuppressWarnings("unchecked")
        Converter<Integer, T> converter = (Converter<Integer, T>) CONVERTERS.get(targetType);
        if (converter == null) {
            converter = new IntegerToEnumConverter<>(targetType);
            CONVERTERS.put(targetType, converter);
        }
        return converter;
    }
}